//
//  LWAreaPicker.swift
//  shop
//
//  Created by 刘伟 on 2017/4/21.
//
//

import UIKit

// 省市区数据的各种 key
let LWAreaIdKey = "value"
let LWAreaTextKey = "text"
let LWAreaChildrenKey = "children"

// MARK: toolbar 的颜色
let ATBarTintColor = UIColor.primary
let ATTintColor = UIColor.white

enum LWAreaType: Int {
    case province
    case city
    case district
}
protocol LWAreaPickerDelegate: class {
    func statusChanged(areaPickerView: LWAreaPicker, pickerView: UIPickerView, textField: UITextField, area: AreaModel)
}

// 组合协议
protocol AreaPickerDelegate: LWAreaPickerDelegate, LWAreaToolbarDelegate {}

class LWAreaPicker: UIView {
    
    var area = AreaModel()
    var cityArray = Array<CityModel>() {
        didSet {
            if cityArray.count > 0 {
                area.id = cityArray[0].id
                area.city = cityArray[0].text
            } else {
                area.city = ""
            }
        }
    }
    var districtArray = Array<DistrictModel>() {
        didSet {
            if districtArray.count > 0 {
                area.id = districtArray[0].id
                area.district = districtArray[0].text
            } else {
                area.district = ""
            }
        }
    }
    var textField: UITextField!
    var pickerView:UIPickerView!
    var toolbar: LWAreaToolbar!
    weak var delegate: LWAreaPickerDelegate?
    
    private init(){
        super.init(frame: CGRect.zero)
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    static func picker<controller: UIViewController>(for controller: controller, textField: UITextField, barTintColor: UIColor = ATBarTintColor, tintColor: UIColor = ATTintColor) -> LWAreaPicker where controller: AreaPickerDelegate {
        
        let areaPickerView = LWAreaPicker()
        areaPickerView.delegate = controller
        areaPickerView.textField = textField
        
        let pickerView = UIPickerView()
        pickerView.backgroundColor = UIColor.white
        areaPickerView.pickerView = pickerView
        
        pickerView.delegate = areaPickerView
        pickerView.dataSource = areaPickerView
        
        
        areaPickerView.area.province = areaPickerView.provinceArray[0].text
        areaPickerView.area.id = areaPickerView.provinceArray[0].id
        areaPickerView.cityArray = areaPickerView.provinceArray[0].children
        if areaPickerView.cityArray.count > 0 {
            areaPickerView.area.province = areaPickerView.cityArray[0].text
            areaPickerView.area.id = areaPickerView.cityArray[0].id
        }
        areaPickerView.districtArray = areaPickerView.cityArray[0].children
        if areaPickerView.districtArray.count > 0 {
            areaPickerView.area.district = areaPickerView.districtArray[0].text
            areaPickerView.area.id = areaPickerView.districtArray[0].id
        }
        textField.inputView = pickerView
        areaPickerView.toolbar = LWAreaToolbar.bar(for: controller, textField: textField, barTintColor: ATBarTintColor, tintColor: ATTintColor)
        textField.inputAccessoryView = areaPickerView.toolbar
        
        return areaPickerView
    }
    
    // MARK: 省数据数组
    var provinceArray: [ProvinceModel] = {
        var $ = [ProvinceModel]()
        let path = Bundle.main.path(forResource: "area", ofType: "plist")
        let areaArray = NSArray(contentsOfFile: path!) as! [[String: AnyObject]]
        for area in areaArray {
            let province = ProvinceModel(data: area)
            $.append(province)
        }
        return $
    }()
    
    func areaSelectedById(areaId: Int) {
        self.area.id = areaId
        var iIndex = 0, jIndex = 0, kIndex = 0
        var province = ""
        var city = ""
        var district = ""
        var ifBreak = false
        for i in 0 ..< self.provinceArray.count {
            if ifBreak { break }
            province = self.provinceArray[i].text
            if self.provinceArray[i].id == areaId {
                iIndex = i
                self.area.province = province
                ifBreak = true
                break
            }
            self.cityArray = self.provinceArray[i].children
            if self.cityArray.count > 0 {
                for j in 0 ..< self.cityArray.count {
                    if ifBreak { break }
                    city = self.cityArray[j].text
                    if self.cityArray[j].id == areaId {
                        iIndex = i
                        jIndex = j
                        self.area.province = province
                        self.area.city = city
                        ifBreak = true
                        break
                    }
                    self.districtArray = cityArray[j].children
                    if self.districtArray.count > 0 {
                        for k in 0 ..< self.districtArray.count {
                            if ifBreak { break }
                            district = self.districtArray[k].text
                            if self.districtArray[k].id == areaId {
                                iIndex = i
                                jIndex = j
                                kIndex = k
                                self.area.province = province
                                self.area.city = city
                                self.area.district = district
                                ifBreak = true
                                break
                            }
                        }
                    }
                }
            }
        }
        pickerView.selectRow(iIndex, inComponent: LWAreaType.province.rawValue, animated: false)
        pickerView.reloadComponent(LWAreaType.city.rawValue)
        pickerView.selectRow(jIndex, inComponent: LWAreaType.city.rawValue, animated: true)
        pickerView.reloadComponent(LWAreaType.district.rawValue)
        pickerView.selectRow(kIndex, inComponent: LWAreaType.district.rawValue, animated: true)
    }
    deinit {
        print("区域选择消失")
    }
}


extension LWAreaPicker: UIPickerViewDelegate, UIPickerViewDataSource {
    
    func numberOfComponents(in pickerView: UIPickerView) -> Int {
        return 3
    }
    
    func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
        let areaType = LWAreaType(rawValue: component)!
        switch areaType {
        case .province:
            return provinceArray.count
        case .city:
            return cityArray.count
        case .district:
            return districtArray.count
        }
    }
    
    func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
        let areaType = LWAreaType(rawValue: component)!
        switch areaType {
        case .province:
            return self.provinceArray[row].text
        case .city:
            if self.cityArray.count > 0 {
                return self.cityArray[row].text
            } else {
                return ""
            }
        case .district:
            if districtArray.count > 0 {
                return self.districtArray[row].text
            } else {
                return ""
            }
        }
    }
    
    func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
        let areaType = LWAreaType(rawValue: component)!
        switch areaType {
        case .province:
            self.cityArray = self.provinceArray[row].children
            pickerView.reloadComponent(LWAreaType.city.rawValue)
            pickerView.selectRow(0, inComponent: LWAreaType.city.rawValue, animated: true)
            reloadDistrictComponent(pickerView: pickerView, row: 0)
            self.area.province = self.provinceArray[row].text
            self.area.id = self.provinceArray[row].id
        case .city:
            reloadDistrictComponent(pickerView: pickerView, row: row)
            if self.cityArray.count > 0 {
                self.area.id = self.cityArray[row].id
                self.area.city = self.cityArray[row].text
            }
        case .district:
            if self.districtArray.count > 0 {
                self.area.district = self.districtArray[row].text
                self.area.id = self.districtArray[row].id
            }
        }
        delegate?.statusChanged(areaPickerView: self, pickerView: pickerView, textField: textField, area: self.area)
    }
    
    func pickerView(_ pickerView: UIPickerView, viewForRow row: Int, forComponent component: Int, reusing view: UIView?) -> UIView {
        let label = UILabel()
        label.textAlignment = .center
        label.contentMode = .center
        label.font = UIFont.systemFont(ofSize: 15)
        label.textColor =  UIColor.black
        let areaType = LWAreaType(rawValue: component)!
        switch areaType {
        case .province:
            label.text = self.provinceArray[row].text
        case .city:
            if self.cityArray.count > 0 {
                label.text = self.cityArray[row].text
            } else {
                label.text = ""
            }
        case .district:
            if self.districtArray.count > 0 {
                label.text = self.districtArray[row].text
            } else {
                label.text = ""
            }
        }
        if label.text!.characters.count > 5 {
            label.font = UIFont.systemFont(ofSize: 12)
        }
        return label
    }
    
    func reloadDistrictComponent(pickerView: UIPickerView, row: Int) {
        guard row <= self.cityArray.count - 1 || row == 0 else {
            return
        }
        if self.cityArray.count > 0 {
            self.districtArray = self.cityArray[row].children
        } else {
            self.districtArray = Array<DistrictModel>()
        }
        pickerView.reloadComponent(LWAreaType.district.rawValue)
        pickerView.selectRow(0, inComponent: LWAreaType.district.rawValue, animated: true)
    }
}

